
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage";
import purchaseApi from "@/api/livestock-manage/purchaseManage/purchase-return-record";
import arrivalApi from "@/api/livestock-manage/purchaseManage/arrival-notice";
import arrivaldetailApi from "@/api/livestock-manage/purchaseManage/arrival-detail";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";
export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      tableColumn: [],
      searchlist: {},
      formConfig: [
        {
          type: "select",
          prop: "returnMethod",
          label: "退货方式",
          options: [
            { name: "退款", value: "退款" },
            { name: "换货", value: "换货" },
            { name: "退货", value: "退货" }
          ],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          type: "select",
          prop: "returnPersonName",
          label: "退货人",
          options: [],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '采购订单编号',
          prop: 'orderNo',
          type: 'input',
        },
        {
          label: '退货产品',
          prop: 'materialNo',
          type: 'select',
          options: [],
          optionKey: { label: 'materialName', value: 'materialNo' },
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "returnMethod",
          selectValue: "",
          typeObj: {
            list: [
              { name: "退款", value: "退款" },
              { name: "换货", value: "换货" },
              { name: "退货", value: "退货" }
            ]
          },
          name: "退货方式",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "returnPersonName",
          selectValue: "returnPersonName",
          typeObj: {},
          name: "退货人",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          selectValue: "",
          typeObj: {},
          name: "采购订单编号",
          required: true,
          notSearch: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "materialName",
          porpObj: "material",
          porpName: "materialName",
          selectValue: "materialNo",
          typeObj: {},
          name: "产品",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "returnQuantity",
          porpObj: "castUnit",
          porpName: "symbol",
          selectValue: "",
          typeObj: {},
          name: "数量",
          required: false,
          notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "vchangerate",
          selectValue: "",
          typeObj: {},
          name: "换算率",
          required: false,
          notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "returnAmount",
          selectValue: "",
          typeObj: {},
          name: "退货金额",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "reason",
          selectValue: "",
          typeObj: {},
          name: "退货原因",
          required: false,
          notSearch: true
        }
      ],
      arrivalList: [],
      arrivalDetailList: [],
      personList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.vchangerate && val.returnQuantity) {
          this.$set(
            val,
            "num",
            isNaN(val.vchangerate * val.returnQuantity)
              ? ""
              : val.vchangerate * val.returnQuantity
          );
        }
      }
    }
  },
  created() {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      if (['returnQuantity'].includes(el.prop)) {
        obj.slotName = 'returnQuantity'
      } else if (['materialName'].includes(el.prop)) {
        obj.slotName = el.prop
      }
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '150' })
    this.tableColumn = list

    this.search();
    this.getPerson();
    this.arrival();
    this.getMaterialList()
  },
  methods: {
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    getMaterialList() {
      materialApi.getqueryList({}).then(res => {
        if (res.code === 1) {
          // this.materialList = res.data;
          this.$set(this.formDatalists[3], 'typeObj', {
            list: res.data,
            listName: ['materialName', 'materialNo']
          })
          this.setOptions(this.formConfig, 'materialNo', res.data)
        }
      });
    },
    // 获取记录人列表
    getPerson() {
      personApi.getStaffListByCondition().then(res => {
        if (res.code === 1) {
          let list = [];
          this.personList = res.data || [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.person.name
            });
          });
          this.formConfig.forEach((item, index) => {
            if (item.prop === "returnPersonName") {
              this.$set(this.formConfig[index], "options", list);
            }
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "returnPersonName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    arrival() {
      arrivalApi.conditionQuery({}).then(res => {
        this.arrivalList = res.data;
      });
    },
    async queryOnHandQuantity(e) {
      if (e) {
        const { data: res } = await arrivaldetailApi.queryListByOrderNo(e);
        this.arrivalDetailList = res;
      } else if (e) {
        this.$message.warning("请重新选择物料");
      }
    },
    batchObjChange(e) {
      // this.$set()
      let formData = { ...this.formData };
      this.$set(formData, "vchangerate", e.exchangeRate);
      // this.$set(formData, "num".e.primaryQuantity);
      if (e.totalPrice) {
        this.$set(formData, "returnAmount", e.totalPrice);
      }
      if (e.arriveNum) {
        this.$set(formData, "returnQuantity", e.arriveNum);
      }
      this.formData = { ...formData, ...e };
      // console.log(e);
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          returnRecordType: "采购",
          ...this.searchlist
        }
      };
      purchaseApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.returnRecordNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      purchaseApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          purchaseApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      this.formData = {
        returnRecordType: "采购"
      };
      this.nowChanceStau = "add";
      this.titleText = "添加退货记录";
      this.addActive = true;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit (row) {
      let index = this.arrivalList.findIndex(el => { return el.orderNo === row.orderNo })
      this.queryOnHandQuantity(this.arrivalList[index].arriveOrderNo)
      this.formData = {
        ...row,
        arriveOrderNo: this.arrivalList[index].arriveOrderNo,
        materialObj: row.material
      };
      this.nowChanceStau = "edit";
      this.titleText = "修改退货记录";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let formData = { ...this.formData };
            purchaseApi.edit(formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let person = { ...this.formData };
            purchaseApi.add(person).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
